package com.example.cloudalibaba.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.example.cloudalibaba.service.PaymentService;
import com.example.springcloud.entity.CommonResult;
import com.example.springcloud.entity.Payment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * @author chensixiang chensixiang1234@gmail.com
 */
@RestController
@Slf4j
public class OrderController {

    @Value("${service-url.nacos-user-service}")
    private String url;
    @Resource
    private RestTemplate restTemplate;

    @GetMapping("/consumer/fallback/{id}")
    // @SentinelResource(value = "fallback") // 没有配置
    // @SentinelResource(value = "fallback", fallback = "handlerFallBack") // 处理业务异常
    // @SentinelResource(value = "fallback", blockHandler = "handlerBlock") // 控制台违规
    // @SentinelResource(value = "fallback", blockHandler = "handlerBlock", fallback = "handlerFallBack") // 都配
    @SentinelResource(value = "fallback",
            blockHandler = "handlerBlock",
            fallback = "handlerFallBack",
            exceptionsToIgnore = IllegalArgumentException.class)
    // 都配
    public CommonResult<Payment> payment(@PathVariable Long id) {
        CommonResult<Payment> result = restTemplate.getForObject(url + "/paymentSQL/" + id, CommonResult.class, id);
        if (id == 4) {
            throw new IllegalArgumentException("非法参数......");
        } else if (result.getData() == null) {
            throw new NullPointerException("没有对应的记录，空指针异常......");
        }
        return result;
    }

    public CommonResult<Payment> handlerFallBack(@PathVariable Long id, Throwable e) {
        Payment payment = new Payment(id, "null");
        return new CommonResult<>(444, "兜底异常handlerFallBack exception的内容:" + e.getMessage(), payment);
    }


    public CommonResult<Payment> handlerBlock(@PathVariable Long id, BlockException e) {
        Payment payment = new Payment(id, "null");
        return new CommonResult<>(445, "blockHandler sentinel 限流 BlockException的内容:" + e.getMessage(), payment);
    }

    @Resource
    private PaymentService paymentService;

    @GetMapping("/sentinel/feign/{id}")
    public CommonResult pay(@PathVariable Long id) {
        return paymentService.paymentSQL(id);
    }
}
